<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>location 对象练习</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            padding: 20px;
        }

        pre {
            background-color: #f4f4f4;
            padding: 15px;
            border-radius: 5px;
            white-space: pre-wrap;
        }

        button {
            margin: 5px 0;
        }
    </style>
</head>
<body>

<h1>location 对象练习</h1>

<h2>当前页面信息：</h2>
<pre id="output"></pre>

<h3>功能测试：</h3>
<button onclick="showLocationInfo()">显示当前 URL 信息</button><br>
<button onclick="goToExample()">跳转到 https://example.com</button><br>
<button onclick="reloadPage()">刷新页面</button><br>
<button onclick="goBack()">返回上一页（如存在）</button><br>
<button onclick="changeQueryParam()">添加查询参数 ?test=1</button>

<script>
    /**
     * location 对象常用属性：
     * - href：完整的 URL
     * - protocol：协议部分（http: 或 https:）
     * - host：主机名 + 端口号
     * - hostname：主机名
     * - port：端口号
     * - pathname：路径部分
     * - search：查询字符串（即 ? 后面的部分）
     * - hash：锚点部分（即 # 后面的内容）
     */

    function getLocationInfo() {
        const info = `
            location.href:        ${location.href}
            location.protocol:    ${location.protocol}
            location.host:        ${location.host}
            location.hostname:    ${location.hostname}
            location.port:        ${location.port || '(默认端口，无显式值)'}
            location.pathname:    ${location.pathname}
            location.search:      ${location.search || '(无查询参数)'}
            location.hash:        ${location.hash || '(无锚点)'}
      `;
        return info;
    }

    function showLocationInfo() {
        document.getElementById("output").textContent = getLocationInfo();
    }

    function goToExample() {
        location.href = "https://example.com";
    }

    function reloadPage() {
        location.reload();
    }

    function goBack() {
        history.back();
    }

    function changeQueryParam() {
        // 添加一个查询参数 ?test=1 到当前 URL
        if (!location.search) {
            location.search = "?test=1";
        } else {
            alert("已有查询参数，无法重复添加");
        }
    }

    // 页面加载时自动显示一次
    window.onload = function () {
        showLocationInfo();
    };
</script>

</body>
</html>
